package algorithm_demo.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 47. 全排列 II
 * <a href="https://leetcode.cn/problems/permutations-ii/">https://leetcode.cn/problems/permutations-ii/</a>
 *
 * @author Api
 * @date 2023/5/5 0:10
 */
public class Problem_047_PermutationsII {
    List<List<Integer>> list2 = new ArrayList<>();

    public List<List<Integer>> permuteUnique(int[] nums) {
        boolean[] used = new boolean[nums.length];
        //排序
        List<Integer> path = new ArrayList<>();
        Arrays.sort(nums);
        dfs(nums, path, used);
        return list2;
    }


    public void dfs(int[] nums, List<Integer> path, boolean[] used) {
        if (path.size() == nums.length) {
            list2.add(new ArrayList<Integer>(path));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            //剪枝条件1：因为每个元素不能重复选取
            if (used[i] == true){
                continue;
            }
            //剪枝条件2：给定数组中有重复值，当前层的重复枝头要被剪掉
            if (i>0 && used[i] == used[i-1] && used[i-1] == false){//如果不加used[i-1]==false时，会重复执行
                continue;
            }
            used[i] = true;
            path.add(nums[i]);
            dfs(nums, path, used);
            path.remove(path.size()-1);
            used[i] = false;
        }
    }
}
